import { PlusOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Modal} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import TagForm from './components/TagForm';
import { TagListItem } from './data.d';
import { tagList, addTag ,updateTag, tagDel, batchDelete} from './service';

const TagList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<TagListItem>({});
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<TagListItem[]>([]);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  
  //添加标签
  const addTagComment  = (values: TagListItem) => {
    new Promise((resolve, reject) => {
      addTag(values)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('添加成功');
            setSelectedRows([]);
            handleModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          }else if(res.code === 4501){
            message.error(res.message);
            resolve(false);
          } else {
            message.error('添加失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('添加失败');
          reject(error);
        });
    });
  }
  
   //编辑标签
   const updateTagComment = (values: TagListItem) => {
    new Promise((resolve, reject) => {
      updateTag(values)
        .then((res) => {
          if (res.code === 200) {
            const hide = message.success('保存成功');
            setSelectedRows([]);
            handleModalVisible(false);
            if (actionRef.current) {
              hide();
              actionRef.current.reload();
            }
            resolve(true);
          }else if(res.code === 4501){
            message.error(res.message);
            resolve(false);
          } else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('保存失败');
          reject(error);
        });
    });
  };

  const handleUpdate = async (values: TagListItem) => {
    if (values != null && values != undefined) {
      let id = values.id;
      if(id){//编辑
        updateTagComment(values);
      }else{//添加
        addTagComment(values);
      }
    }
  };

  //删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此标签将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          const param = new Object();
          param["id"] = id;
          tagDel(param)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowKeys.length > 0) {
                    for (var i in selectedRowKeys) {
                      if (selectedRowKeys[i] == id) {
                        selectedRowKeys.splice(parseInt(i), 1);
                      }
                    }
                  }
                  hide();
                  if (selectedRowKeys.length == 0) {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    const newRows = selectedRows.concat();
                    for(let i=0;i<selectedRows.length;i++){
                      if(selectedRows[i].id == id){
                        newRows.splice(i, 1);
                      }
                    }
                    setSelectedRows(newRows);
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
                }else if(res.code === 4501){
                  message.error('该标签在使用中，暂不可删除');
                  resolve(false);
                }else {
                  message.error('删除失败，' + res.message);
                  resolve(false);
                }
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  //批量删除--删除弹出框
  const delConfirmBatch = (ids: string) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此标签将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          const param = new Object();
          param["ids"] = ids;
          batchDelete(param)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  const errList = res.data;
                  if(errList.length == 0){
                    message.success("删除成功",1);
                  }else{
                    let mes = "";
                    for(let i in errList){
                      for(let j in selectedRows){
                        if(parseInt(selectedRows[j].id) == errList[i]){
                          mes += selectedRows[j].name + '，';
                        }
                      }
                    }
                    mes = mes + "删除失败";
                    message.error(mes,2);
                  }
                  handleDeleteModalVisible(false);
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                  resolve(true);
                } else {
                  message.error('删除失败，'+res.message);
                  resolve(false);
                }
              }else{
                message.error('删除失败');
                  resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  const columns: ProColumns<TagListItem>[] = [
    {
      title: '所属机构名',
      dataIndex: 'topOrgName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '标签名称',
      dataIndex: 'name',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '是否使用中',
      dataIndex: 'status',
      valueType: 'text',
      hideInSearch: true, 
      valueEnum: {
        true: { text: '是', status: 'Success' },
        false: { text: '否', status: 'Warning' },
      },
    },
    {
      title: '更新时间',
      dataIndex: 'datetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a 
           disabled={record.status}
           onClick={() => {
            delConfirm(record.id);
          }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TagListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => {
              handleModalVisible(true);
              setFormValues({});
            }}>
            <PlusOutlined /> 新建标签
          </Button>,
          <Button type="primary" 
          disabled={selectedRows.length > 0 ? false : true}
          onClick={() => delConfirmBatch(selectedRows.map((row) => row.id).toString())}>
            <DeleteOutlined /> 批量删除
          </Button>,
        ]}
        request={(params, sorter, filter) => tagList({ ...params, sorter, filter })}
        columns={columns}
        onLoad={()=>{
          setSelectedRowKeys(selectedRowKeys);
          setSelectedRows(selectedRows);
        }}
        rowSelection={{
          selectedRowKeys:selectedRowKeys,
          getCheckboxProps: record => ({
            disabled: record.status === true, // status是true不可选
          }),
          onSelect:(record, selected)=>{
            if(selected){//选中
              setSelectedRowKeys([...selectedRowKeys,record.key]);
              setSelectedRows([...selectedRows,record]);
            }else{//取消选中
              const newKeys = selectedRowKeys.concat();
              const index = newKeys.indexOf(record.key);
              newKeys.splice(index, 1);
              setSelectedRowKeys(newKeys);
              
              const newRows = selectedRows.concat();
              for(let i=0;i<selectedRows.length;i++){
                if(i == index){
                  newRows.splice(index, 1);
                }
              }
              setSelectedRows(newRows);
            }
          },
          onSelectAll:(selected, selectedRows1, changeRows)=>{
            if(selected){//全选
              const keys = [];
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                keys.push(record.key);
              }
              setSelectedRowKeys([...selectedRowKeys,...keys]);
              setSelectedRows([...selectedRows,...changeRows]);
            }else{//取消全选
              const newSelectedRowKeys = selectedRowKeys.concat();
              const newSelectedRows = selectedRows.concat();
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                for(let j=0;j<newSelectedRowKeys.length;j++){
                  if(record.key == newSelectedRowKeys[j]){
                    newSelectedRowKeys.splice(j, 1);
                    newSelectedRows.splice(j, 1);
                  }
                }
              }
              setSelectedRowKeys(newSelectedRowKeys);
              setSelectedRows(newSelectedRows);
            }
          }
        }}
        tableAlertOptionRender={() => {
          return (<a onClick={() => {
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.clearSelected?.();
          }}>清空</a>)
        }}
      />
      <TagForm 
        onCancel={() => handleModalVisible(false)} 
        modalVisible={createModalVisible} 
        values={formValues}
        onSubmit={handleUpdate}
        >
          <ProTable<TagListItem, TagListItem> />
      </TagForm>
    </PageContainer>
  );
};

export default TagList;
